import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bitcoin/flutter_bitcoin.dart';
import 'package:http/http.dart' as http;
import 'package:bip39/bip39.dart' as bip39;
import 'package:http/http.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHome1Page(title: 'Flutter Demo Home Page'),
    );
  }
}

// class MyHomePage extends StatefulWidget {
//   const MyHomePage({super.key, required this.title});
//
//   // This widget is the home page of your application. It is stateful, meaning
//   // that it has a State object (defined below) that contains fields that affect
//   // how it looks.
//
//   // This class is the configuration for the state. It holds the values (in this
//   // case the title) provided by the parent (in this case the App widget) and
//   // used by the build method of the State. Fields in a Widget subclass are
//   // always marked "final".
//
//   final String title;
//
//   @override
//   State<MyHomePage> createState() => _MyHomePageState();
// }
//
// class _MyHomePageState extends State<MyHomePage> {
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         backgroundColor: Theme.of(context).colorScheme.inversePrimary,
//         title: Text(widget.title),
//       ),
//       body: Center(
//         child: Container(
//           padding: const EdgeInsets.all(30),
//           child: Column(
//             mainAxisAlignment: MainAxisAlignment.center,
//             children: <Widget>[
//               Text(
//                 mnemonic ?? "No mnemonic",
//                 style: TextStyle(color: findOne ? Colors.red : Colors.black),
//               ),
//               const SizedBox(
//                 height: 20,
//               ),
//               Row(
//                 mainAxisAlignment: MainAxisAlignment.center,
//                 children: [
//                   GestureDetector(
//                     behavior: HitTestBehavior.opaque,
//                     onTap: () {
//                       copyText();
//                     },
//                     child: Container(
//                       padding: const EdgeInsets.all(10),
//                       decoration: BoxDecoration(
//                         borderRadius: BorderRadius.circular(10),
//                         color: Colors.blue,
//                       ),
//                       child: const Text('点击复制'),
//                     ),
//                   )
//                 ],
//               ),
//               const SizedBox(
//                 height: 50,
//               ),
//               Text(address ?? 'no address'),
//               const SizedBox(
//                 height: 50,
//               ),
//               Text('BTC 余额: ${balance ?? 0 / 100000000} BTC'),
//             ],
//           ),
//         ),
//       ),
//       floatingActionButton: FloatingActionButton(
//         onPressed: isScanning ? stopScan : startScan,
//         tooltip: 'Increment',
//         child: isScanning
//             ? const Icon(Icons.stop_circle)
//             : const Icon(Icons.not_started_sharp),
//       ), // This trailing comma makes auto-formatting nicer for build methods.
//     );
//   }
//
//   String? mnemonic;
//
//   String? address;
//   int? balance;
//
//   bool isScanning = false;
//
//   bool findOne = false;
//
//   Future<void> startScan() async {
//     setState(() {
//       isScanning = true;
//     });
//     for (int i = 0; i < 100000000000000000; i++) {
//       if (isScanning == false) {
//         break;
//       }
//       beginTry();
//       final url = 'https://blockchain.info/balance?active=$address';
//
//       try {
//         final response = await http.get(Uri.parse(url));
//
//         if (response.statusCode == 200) {
//           var data = json.decode(response.body);
//           balance = data[address]['final_balance'];
//         } else {
//           balance = 0;
//         }
//       } catch (e) {
//         balance = 0;
//       }
//       setState(() {});
//       if ((balance ?? 0) > 0) {
//         setState(() {
//           findOne = true;
//           copyText();
//         });
//         break;
//       }
//     }
//   }
//
//   void stopScan() {
//     setState(() {
//       isScanning = false;
//     });
//   }
//
//   void beginTry() {
//     setState(() {
//       // 生成24位随机助记词
//       mnemonic = bip39.generateMnemonic(strength: 256); // 24个单词
//
//       // 通过助记词生成种子
//       var seed = bip39.mnemonicToSeed(mnemonic!);
//
//       // 使用种子生成HD钱包
//       var hdWallet = HDWallet.fromSeed(seed);
//
//       // 获取比特币地址
//       address = hdWallet.address;
//     });
//   }
//
//   void copyText() {
//     Clipboard.setData(ClipboardData(text: mnemonic!));
//   }
// }

class MyHome1Page extends StatefulWidget {
  const MyHome1Page({super.key, required this.title});

  final String title;

  @override
  State<MyHome1Page> createState() => _MyHome1PageState();
}

class _MyHome1PageState extends State<MyHome1Page> {
  List<Map<String, dynamic>> everyList = [
    {'color': Colors.red, 'percent': 20},
    {'color': Colors.yellow, 'percent': 0},
    {'color': Colors.green, 'percent': 100},
    {'color': Colors.blue, 'percent': 99},
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Conditional Rendering Example'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            children: [
              ...List.generate(
                  4,
                  (index) => _buildEvery(
                      percent: everyList[index]['percent'],
                      color: everyList[index]['color'],
                      height: 30))
            ],
          ),
        ),
      ),
    );
  }

  /// 选中颜色、百分比、行高
  Widget _buildEvery({Color? color, int? percent, double? height}) {
    return Container(
      /// 控制间隔
      margin: const EdgeInsets.only(top: 20),
      child: LayoutBuilder(builder: (context, constraints) {
        const textStyle = TextStyle(fontSize: 14);
        final textPainter = TextPainter(
          text: TextSpan(text: '$percent%', style: textStyle),
          textDirection: TextDirection.ltr,
          maxLines: 1,
        )..layout(maxWidth: constraints.maxWidth);
        final isTextFits = textPainter.width + 16 <=
            constraints.maxWidth * (100 - (percent ?? 0)) / 100;

        return Row(
          children: [
            if ((percent ?? 0) > 0)
              Expanded(
                flex: percent ?? 0,
                child: Container(
                  width: double.infinity,
                  height: height,
                  decoration: BoxDecoration(
                    color: color,
                    borderRadius: (percent ?? 0) == 100
                        ? BorderRadius.circular(8)
                        : const BorderRadius.only(
                            topLeft: Radius.circular(8), // 左上角圆角
                            bottomLeft: Radius.circular(8), // 左下角圆角
                          ),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      if (!isTextFits)
                        Padding(
                          padding: const EdgeInsets.only(right: 8, left: 8),
                          child: Text(
                            '$percent%',
                            style: textStyle,
                          ),
                        )
                    ],
                  ),
                ),
              ),
            if ((percent ?? 0) < 100)
              Expanded(
                flex: 100 - (percent ?? 0),
                child: Container(
                  width: double.infinity,
                  height: height,
                  decoration: BoxDecoration(
                    /// 未选中的颜色
                    color: Colors.grey,
                    borderRadius: (percent ?? 0) == 0
                        ? BorderRadius.circular(8)
                        : const BorderRadius.only(
                            topRight: Radius.circular(8), // 左上角圆角
                            bottomRight: Radius.circular(8), // 左下角圆角
                          ),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      if (isTextFits)
                        Padding(
                          padding: const EdgeInsets.only(left: 8),
                          child: Text(
                            '$percent%',
                            style: textStyle,
                          ),
                        )
                    ],
                  ),
                ),
              )
          ],
        );
      }),
    );
  }
}
